const { app, BrowserWindow, BrowserView, protocol, ipcMain} = require('electron')
const { readFile } = require ('fs')
const { URL } =  require ('url')
const path = require('path')

module.exports=function(){
    console.log("protocol.js");
    protocol.registerSchemesAsPrivileged([
        { scheme: 'xrpa', privileges: { bypassCSP: true, standard: true, corsEnabled:true } },
    ])
}

// 注册自定义协议
module.exports.setDefaultProtocol = function(app, scheme){
    let isSet = false // 是否注册成功
    app.removeAsDefaultProtocolClient(scheme) // 每次运行都删除自定义协议 然后再重新注册
    isSet = app.setAsDefaultProtocolClient(scheme)
    console.log('是否注册成功', isSet)
}


// 处理文件打包之后的访问路径为 app的相对路径,
module.exports.createProtocol = function(app, scheme) {
    protocol.registerBufferProtocol(
      scheme,
      (request, respond) => {
        console.log('request', request);
        let host = new URL(request.url).host
        let pathName = new URL(request.url).pathname
        console.log("pathName1", pathName);
        if(pathName == '/'){
            pathName = '/index.html'
        }
        pathName = host + pathName;
        console.log("pathName2", pathName);
        pathName = decodeURI(pathName) // Needed in case URL contains spaces
        readFile(path.join(__dirname, "../"+pathName), (error, data) => {
          if (error) {
            console.error(`Failed to read ${pathName} on ${scheme} protocol`, error)
          }
          const extension = path.extname(pathName).toLowerCase()
          let mimeType = ''
          if (extension === '.js') {
            mimeType = 'text/javascript'
          } else if (extension === '.html') {
            mimeType = 'text/html'
          } else if (extension === '.css') {
            mimeType = 'text/css'
          } else if (extension === '.svg' || extension === '.svgz') {
            mimeType = 'image/svg+xml'
          } else if (extension === '.json') {
            mimeType = 'application/json'
          }
          respond({ mimeType, data })
        })
      },
      error => {
        if (error) {
          console.error(`Failed to register ${scheme} protocol`, error)
        }
      }
    )
}
